/*
 * @Description: 用户信息相关
 * @Project: 
 * @Author: michelle
 * @Date: 2022-02-22 18:26:23
 * @LastEditors: michelle
 * @LastEditTime: 2022-02-23 18:18:40
 * @Modified By: michelle
 * @FilePath: /vite-project/src/store/userSlice.jsx
 */

import { createSlice } from '@reduxjs/toolkit'
import { LOCAL_STORAGE } from '../../config'
import { isPlainObject } from 'lodash'
// import { serviceLoginByToken } from '@/services'


let localUser
try {
  const r = JSON.parse(localStorage.getItem(LOCAL_STORAGE.USER))
  if (isPlainObject(r)) {
    localUser = r
  }
} catch {}

const initialState = {
  isLogin: !!localUser,
  isLockScreen: false,
  userInfo: localUser || {
    uid: undefined, // 用户ID
    username: '', // 昵称
    password: '', // 经过MD5加密后的密码
    loginName: '', // 登录名
    avatarUrl: '', // 头像
    token: undefined, // 登录凭证
    location: ''
  }
}

export const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    SET_USER_INFO: (state, action) => {
      const userInfo = action.payload
      if (userInfo.token) {
        state.isLogin = true
        localStorage.setItem(LOCAL_STORAGE.USER, JSON.stringify(userInfo))
        localStorage.setItem(LOCAL_STORAGE.LOGIN_NAME, userInfo.loginName)
      }
      state.userInfo = userInfo
    }
  }
})

export const { SET_USER_INFO } = userSlice.actions

//token获取
export const loginByToken = (token) => (dispatch) => {
//   return serviceLoginByToken(token).then(res => {
//     const userInfo = res.userInfo
//     return dispatch(SET_USER_INFO(userInfo))
//   })
}

export default userSlice.reducer
